package org.example.facade.panel;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.transform.Affine;
import org.example.physics_engine.body.PhysicsBody;
import org.example.physics_engine.body.Transform;
import org.example.physics_engine.geometry.shapes.AbstractShape;

public class ImgRenderer implements PanelRenderer{

    private final Image image;

    public ImgRenderer(Image image) {
        this.image = upsideDown(image);
    }

    public ImgRenderer(String resource){
        this(new Image(ImgRenderer.class.getClassLoader().getResourceAsStream(resource)));
    }

    //上下反转图片

    public static WritableImage upsideDown(Image image){
        int w = (int) image.getWidth();
        int h = (int) image.getHeight();
        PixelReader pixelReader = image.getPixelReader();
        WritableImage writableImage = new WritableImage(w, h);
        PixelWriter pixelWriter = writableImage.getPixelWriter();

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                pixelWriter.setArgb(j, h - 1 - i, pixelReader.getArgb(j, i));
            }
        }

        return writableImage;


    }

    @Override
    public void drawToCanvas(GraphicsContext graphicsContext, PhysicsBody physicsBody) {
        AbstractShape shape = physicsBody.getShape();
        Transform transform = shape.getTransform();
        int scale = shape.getRate();

        final int gridSize = 30; // TODO how to get gridSize or render without gridSize

        Affine affine = new Affine();
        affine.appendRotation(transform.getRotationAngle(), transform.getX(), transform.getY());
        //affine.appendRotation(transform.getAngle(), transform.x, transform.y);
        //gc.save();
        graphicsContext.save();
        //gc.transform(affine);
        graphicsContext.transform(affine);
        graphicsContext.drawImage(image,
                transform.getX() - gridSize / 2.0 * scale,
                transform.getY() - gridSize / 2.0 * scale,
                gridSize * scale, gridSize * scale);
        graphicsContext.restore();
    }
}
